<template>
  <a-modal
    :open="open"
    :title="title"
    width="600px"
    :body-style="{ maxHeight: '600px', overflowY: 'auto', padding: '20px 24px' }"
    @update:open="(val) => $emit('update:open', val)"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk">保存设备</a-button>
    </template>

    <a-form ref="formRef" layout="vertical" :model="formState">
      <div
        v-for="(equipment, index) in formState.equipmentList"
        :key="equipment.id"
        class="equipment-section"
      >
        <div class="equipment-header">
          <span class="equipment-title">设备 {{ index + 1 }}</span>
        </div>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              :name="['equipmentList', index, 'equipmentType']"
              :rules="[{ required: true, message: '请选择设备类型' }]"
            >
              <template #label>
                <span>设备类型</span>
              </template>
              <a-select
                v-model:value="equipment.equipmentType"
                placeholder="请选择设备类型"
                allow-clear
                :options="equipmentTypeOptions"
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              :name="['equipmentList', index, 'equipmentQuantity']"
              :rules="[
                { required: true, message: '请输入数量' },
                { pattern: /^[1-9]\d*$/, message: '请输入正整数' },
              ]"
            >
              <template #label>
                <span>设备数量</span>
              </template>
              <a-input
                v-model:value="equipment.equipmentQuantity"
                placeholder="请输入数量"
                allow-clear
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :name="['equipmentList', index, 'equipmentStatus']"
          :rules="[{ required: true, message: '请选择设备状态' }]"
        >
          <template #label>
            <span>设备状态</span>
          </template>
          <a-select
            v-model:value="equipment.equipmentStatus"
            placeholder="请选择设备状态"
            allow-clear
            :options="equipmentStatusOptions"
          />
        </a-form-item>

        <a-form-item
          :name="['equipmentList', index, 'equipmentPosition']"
          :rules="[{ required: true, message: '请选择设备位置' }]"
        >
          <template #label>
            <span>设备位置</span>
          </template>
          <a-textarea
            v-model:value="equipment.equipmentPosition"
            readonly
            placeholder="请选择设备位置"
            :rows="2"
          />
          <a-button style="padding: 4px 0" type="link" @click="showLocationModal(index)">
            <EnvironmentOutlined /> 选择地点
          </a-button>
        </a-form-item>

        <a-form-item :name="['equipmentList', index, 'remark']">
          <template #label>
            <span>备注</span>
          </template>
          <a-textarea
            v-model:value="equipment.remark"
            placeholder="请输入备注信息"
            :rows="3"
            :maxlength="200"
            show-count
            allow-clear
          />
        </a-form-item>

        <a-divider v-if="formState.equipmentList.length > 1" />
      </div>

      <a-button type="link" class="add-equipment-btn" @click="addEquipment">
        <template #icon>
          <span style="font-size: 16px">+</span>
        </template>
        继续添加设备
      </a-button>
    </a-form>
  </a-modal>

  <!-- 地图选择弹窗 -->
  <a-modal
    v-model:open="locationModalVisible"
    title="选择设备位置"
    width="1200px"
    :footer="null"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <TencentMap
      :initial-location="selectedMapLocation"
      :initial-address="currentLocationAddress"
      @location-selected="handleLocationSelected"
    />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import type { FormInstance } from 'ant-design-vue'
import { EnvironmentOutlined } from '@ant-design/icons-vue'
import TencentMap from '@/components/tencentMap.vue'

interface Equipment {
  id: number
  equipmentType?: string
  equipmentQuantity?: string
  equipmentPosition?: string
  equipmentStatus?: string
  remark?: string
}

interface FormState {
  equipmentList: Equipment[]
}

const props = defineProps<{
  open: boolean
  title: string
  rowData?: any
}>()

const emit = defineEmits(['update:open', 'success'])

// 表单引用
const formRef = ref<FormInstance>()

// 地图相关数据
const locationModalVisible = ref(false)
const selectedMapLocation = ref({ lat: 30.08, lng: 120.49 }) // 默认绍兴柯桥
const currentLocationAddress = ref('')
const currentEditingIndex = ref<number>(-1)

// 设备类型选项
const equipmentTypeOptions = ref([
  { label: '摄像头', value: 'camera' },
  { label: '传感器', value: 'sensor' },
  { label: '信号灯', value: 'trafficLight' },
  { label: '显示屏', value: 'display' },
])

// 设备状态选项
const equipmentStatusOptions = ref([
  { label: '正常', value: 'normal' },
  { label: '维修中', value: 'maintenance' },
  { label: '故障', value: 'fault' },
  { label: '停用', value: 'disabled' },
])

// 表单数据
let equipmentIdCounter = 1
const formState = reactive<FormState>({
  equipmentList: [
    {
      id: equipmentIdCounter++,
      equipmentType: undefined,
      equipmentQuantity: undefined,
      equipmentPosition: undefined,
      equipmentStatus: 'normal',
      remark: undefined,
    },
  ],
})

// 监听 rowData 变化，用于编辑时回填数据
watch(
  () => props.rowData,
  (newVal) => {
    if (newVal && newVal.equipmentList && newVal.equipmentList.length > 0) {
      formState.equipmentList = newVal.equipmentList.map((item: any, index: number) => ({
        id: index + 1,
        ...item,
      }))
      equipmentIdCounter = formState.equipmentList.length + 1
    }
  },
  { immediate: true, deep: true },
)

// 添加设备
const addEquipment = () => {
  formState.equipmentList.push({
    id: equipmentIdCounter++,
    equipmentType: undefined,
    equipmentQuantity: undefined,
    equipmentPosition: undefined,
    equipmentStatus: 'normal',
    remark: undefined,
  })
}

// 显示地图选择弹窗
const showLocationModal = (index: number) => {
  currentEditingIndex.value = index
  const currentPosition = formState.equipmentList[index].equipmentPosition
  currentLocationAddress.value = currentPosition || ''
  locationModalVisible.value = true
}

// 处理地图位置选择
const handleLocationSelected = (locationData: { lat: number; lng: number; address: string }) => {
  if (currentEditingIndex.value >= 0) {
    formState.equipmentList[currentEditingIndex.value].equipmentPosition = locationData.address
  }
  selectedMapLocation.value = { lat: locationData.lat, lng: locationData.lng }
  locationModalVisible.value = false
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  formState.equipmentList = [
    {
      id: 1,
      equipmentType: undefined,
      equipmentQuantity: undefined,
      equipmentPosition: undefined,
      equipmentStatus: 'normal',
      remark: undefined,
    },
  ]
  equipmentIdCounter = 2
}

// 提交表单
const handleOk = async () => {
  try {
    await formRef.value?.validate()

    // 这里可以调用API保存数据
    console.log('表单数据:', formState.equipmentList)

    emit('success', formState.equipmentList)
    emit('update:open', false)
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 取消
const handleCancel = () => {
  emit('update:open', false)
  resetForm()
}
</script>

<style lang="scss" scoped>
.equipment-section {
  position: relative;
}

.equipment-header {
  margin-bottom: 16px;
}

.equipment-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.equipment-divider {
  width: 100%;
  height: 1px;
  background: linear-gradient(
    90deg,
    rgba(64, 158, 255, 0) 0%,
    rgba(64, 158, 255, 0.3) 50%,
    rgba(64, 158, 255, 0) 100%
  );
  margin: 24px 0;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: -1px;
    width: 100%;
    height: 1px;
    background: linear-gradient(
      90deg,
      rgba(64, 158, 255, 0) 0%,
      rgba(64, 158, 255, 0.5) 50%,
      rgba(64, 158, 255, 0) 100%
    );
  }
}

.add-equipment-btn {
  width: 100%;
  height: 48px;
  border: 1px dashed #409eff;
  border-radius: 4px;
  color: #409eff;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 16px;
  transition: all 0.3s;

  &:hover {
    background-color: rgba(64, 158, 255, 0.05);
    border-color: #66b1ff;
  }
}

:deep(.ant-form-item-label) {
  padding-bottom: 4px;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

// 优化滚动条样式
:deep(.ant-modal-body) {
  // Webkit浏览器滚动条样式
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
    transition: background 0.3s;

    &:hover {
      background: #a8a8a8;
    }
  }

  // Firefox滚动条样式
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}
</style>
